<template>
<div>
  <el-dialog
      v-model="visible"
      :title="$t('loc.selMse')"
      width="50%"
      top="4vh"
      :close-on-click-modal="false"
      :before-close="handleClose"

  >
    <el-tree
        ref="TreeRef"
        :data="frameworksData"
        :props="frameworksProps"
        node-key ="id"
        show-checkbox
        default-expand-all
        :default-checked-keys="defaultSelectMeasureIds"
    >
    </el-tree>
    <template #footer>
      <span class="dialog-footer">
      <el-button @click="handleClose">{{ $t('loc.cancel') }}</el-button>
      <el-button type="primary" @click="handleConfirm">{{ $t('loc.confirm') }}</el-button>
    </span>
    </template>
  </el-dialog>
</div>
</template>

<script>
export default {
  name: "FrameworkMeasureSelect",
  props: {
    frameworks: {
      type: Array,
      required: true
    },
    dialogVisible: {
      type: Boolean,
      required: true
    },
    selectMeasureIds: {
      type: Array,
      required: true
    }
  },
  data() {
    return {
      visible: false,
      frameworksProps: {
        children: 'childDomains',
        label: 'label',
      },
      frameworksData: [],
      defaultSelectMeasureIds: [] // 默认
    }
  },
  watch: {
    frameworks: {
      immediate: true,
      handler(newVal) {
        // 将 newVal 下所以深度的 name 和 abbreviation 组合成新的数组
        this.frameworksData = this.getChildren(newVal)
      }
    },
    dialogVisible: {
      immediate: true,
      handler(newVal) {
        this.visible = newVal
        if (newVal) {
          this.defaultSelectMeasureIds = this.selectMeasureIds
        }
      },
    },
  },
  computed: {

  },
  methods: {
    getChildren(frameworks) {
      if (!frameworks || frameworks.length === 0) {
        return []
      }
      let arr = []
      frameworks.forEach(item => {
        let data = {
          label: item.abbreviation ? `${item.abbreviation}-${item.name}` : item.name,
          childDomains: this.getChildren(item.childDomains),
        }
        if(data.childDomains.length === 0) {
          data.id = item.id
        }
        arr.push(data)
      })
      return arr
    },
    handleClose() {
      this.visible = false
      this.$emit('update:dialogVisible', this.visible)
      this.defaultSelectMeasureIds = []
      this.$nextTick(() => {
        this.$refs.TreeRef.setCheckedKeys([]);
      });
    },
    handleConfirm () {
      let selectMeasures = this.$refs.TreeRef.getCheckedNodes() || []
      this.$emit('selectedMeasureIds', selectMeasures.filter(item=>item.id).map(item=>item.id))
      this.handleClose()
    }
  }
}
</script>

<style scoped>

</style>